#include "draw.h"
#include "phitron.h"
#include "physics.h"

#include <iostream>

extern phitron::Group<TOTAL_FORCES> group;
bool toDraw = true;

namespace draw
{
	GLfloat light_ambient[] = {0.05, 0.05, 0.05, 1.0};
	GLfloat light_diffuse[] = {0.5, 0.5, 0.5, 1.0};
	GLfloat light_specular[] = {1.0, 1.0, 1.0, 1.0};
	GLfloat light_position[] = {1.0, 1.0, 1.0, 0.0};

	void init() {
		glEnable(GL_DEPTH_TEST);
		glEnable(GL_CULL_FACE);
		glDepthFunc(GL_LEQUAL);
		glShadeModel(GL_SMOOTH);
		glEnable(GL_COLOR_MATERIAL);
		//glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
		//glClearDepth(1.0f);
		glClearColor(0.0, 0.0, 0.0, 1.0);
		//glDepthRange(0.0, 1.0);

		glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
		glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
		glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
		glLightfv(GL_LIGHT0, GL_POSITION, light_position);

		glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);

		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
		glFrustum(-1920.0/1080.0, 1920.0/1080.0, -1, 1, 1.0, 3000.0);

		glMatrixMode(GL_MODELVIEW);

		glNewList(SPHERE, GL_COMPILE);
			sphere(SPHERE_QUALITY);
		glEndList();
	}

	void v3d(Vector3 a) {
		glVertex3d(a.x, a.y, a.z);
	}
	void n3d(Vector3 a) {
		glNormal3d(a.x, a.y, a.z);
	}
	void t3d(Vector3 a) {
		glTranslated(a.x, a.y, a.z);
	}
	void r3d(Vector3 a) {
		double mag = a.magnitude();
		a = a / mag;
		glRotated(mag/M_PI*180, a.x, a.y, a.z);
	}
	void m3d(Matrix3 a) {
		GLdouble mat[] = {a.x.x, a.x.y, a.x.z, 0.0,
						  a.y.x, a.y.y, a.y.z, 0.0,
					  	  a.z.x, a.z.y, a.z.z, 0.0,
					  	  0.0, 0.0, 0.0, 1.0};
		glLoadMatrixd(mat);
	}

	float back = 0;

	void draw() {
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glPushMatrix();

		back += 0.01;
		glLightfv(GL_LIGHT0, GL_POSITION, light_position);

		/*
		glDisable(GL_CULL_FACE);
		glBegin(GL_QUADS);
		glNormal3d(0.0, 1.0, 0.0);
		for (int x = -20; x < 20; x++)
			for (int z = -20; z < 20; z++) {
				glColor3f(0, (z+x+60)%2, (z+x+61)%2);
				glVertex3d(x-0.5, -1, z-0.5);
				glVertex3d(x-0.5, -1, z+0.5);
				glVertex3d(x+0.5, -1, z+0.5);
				glVertex3d(x+0.5, -1, z-0.5);
			}
		glEnd();
		glEnable(GL_CULL_FACE);*/

		glColor3f(1.0, 1.0, 1.0);

		if (toDraw)
			for (Link<phitron::Object<TOTAL_FORCES>>* link = group.objects; link; link = link->next) {
				glPushMatrix();
				t3d(link->object.position);
				glCallList(SPHERE);
				glPopMatrix();
			}

		glPopMatrix();
	}
}
